import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image, ScrollView } from '@tarojs/components'
import './companydetail.scss'
import { AtTabBar, AtAvatar, AtTabs, AtTabsPane, AtToast, AtIcon } from 'taro-ui'
import { DNavBar, DCarInfo, DModal, DItemError, DLookImages } from '@/components'
import MortageList from '../mortgage/MortageList'
import http from '@/api'
import sdk from '@/common/sdk'
const bg = require('../assets/head-portrait.png')
const icon_message = require('../assets/icon_chat.png')
const icon_phone = require('../assets/icon_phone.png')
const icon_star = require('../assets/icon_favorite.png')
const icon_star2 = require('../assets/start_2.png')
export default class Index extends Component {

    constructor(props) {
        super(props)
        this.state = {
            active: 3,
            current: 0,
            isToast: false,
            icon: '',
            collect: '收藏',
            isShow: false,
            text: '',
            list: {
                creatorContact: ''
            },
            item: [],
            item2: [],
            item3: [],
            id: '',
            scrollStyle: window.screen.availHeight,
            page: 1,
            limit: 10,
            order: "",
            sidx: "",
            status: "1",
            totalPage: 1,
            footerStatus: false,
            imageUrl: "",
            companycar: {
                itemStatus: false,
                itemUrl: ''
            },
            knowUrl: [],
            orderNumber: 0
        }
    }

    componentWillMount = () => {
        let { id = 1, tab = 0, type } = this.$router.params
        this.setState({
            id,
            current: +tab
        })

        this.getList(id)
        this.getItem(id)
        this.isCollect()
        this.getOrderNumber(id)
    }

    componentDidShow() {
        let { type, id } = this.$router.params
        this.getList(id)
        if (type) {
            sdk.setTitleInfo('车商')
        } else {
            sdk.setTitleInfo('企业详情')
        }

    }

    // 获取订单数量
    async getOrderNumber(entId) {
        let res = await http.getCorpTradeOrderCount(entId)
        let res2 = await http.getCorpTransportOrderCount(entId)
        this.setState({
            orderNumber: res + res2
        })
    }

    //加载企业信息
    getList(id) {
        http.getEnterpriseDetail({ id: id }).then(res => {
            if (!res) {
                return
            }
            let list = res
            let imageUrl1, imageUrl2
            list.fileList.map(item => {
                if (item.cfType === '4') {
                    imageUrl1 = item.cfFileUrl
                }
                if (item.cfType === '1') {
                    imageUrl2 = item.cfFileUrl
                }
            })
            this.setState({
                list,
                imageUrl1,
                imageUrl2,
                knowUrl: list.fileList
            })
        })
    }
    //加载企业车源列表
    getItem(id) {
        let { page, limit, order, sidx, status, totalPage, item2 } = this.state
        const { type, tab } = this.$router.params
        let obj = {
            entId: `${id}`,
            page,
            limit,
            order,
            sidx,
            status,
            carBussType: '1'
        }
        if (page > totalPage) {
            this.setState({
                footerStatus: true
            })
            return
        }

        if (+tab >= 0) {
            http.getSearchCars({ type, page, limit, entId: id || this.$router.params.id }).then(res => {
                if (!res) {
                    return
                }
                let as = item2.concat(res.list)
                this.setState({
                    item2: as,
                    item: item2.concat(res.list),
                    totalPage: res.totalPage
                })
            })
        } else {
            // http.getenterList(obj).then(res => {
            http.carSourceListByEnt(obj).then(res => {
                if (!res) {
                    return
                }
                this.setState({
                    item2: item2.concat(res.list),
                    item: item2.concat(res.list),
                    totalPage: res.totalPage
                })
            })
        }
    }
    isCollect() {
        let { id } = this.$router.params
        http.isCollect(id).then(res => {
            if (res) {
                this.setState({
                    active: 2,
                    collect: '已收藏',
                })
            }
        })
    }
    //修改tab
    handleClick(value) {
        let item = value === 1 ? this.state.item2 : this.state.item3
        this.setState({
            current: value,
            item
        })
    }
    onScroll = () => {
        this.setState({
            page: this.state.page + 1
        }, () => this.getItem())
    }
    onHandleActive(value) {
        // if (value === 1) {
        //     this.setState({
        //         isShow: true
        //     })
        // } else if (value === 0 && window.bridge) {
        //     const { list } = this.state
        //     // window.bridge.callHandler('IMChat', { 'tephone': list.creatorContact }, function responseCallback(res) { })
        //     sdk.setWechatInfo(list.creatorContact, 0, '企业详情')
        // }
        // if (value === 2 && this.state.active == 2) {
        //     this.delmyCarCollect()
        // } else if (value === 2 && this.state.active == 3) {
        //     this.addmyCarCollect()
        // }

        if (value === 0) {
            this.setState({
                isShow: true
            })
        }

        if (value === 1 && this.state.active == 2) {
            this.delmyCarCollect()
        } else if (value === 1 && this.state.active == 3) {
            this.addmyCarCollect()
        }
    }
    addmyCarCollect() {
        let obj = {
            "mcBussId": this.state.id,
            "mcBussType": 2
        }
        http.addmyCarCollect(obj).then(() => {
            setTimeout(() => {
                this.setState({
                    isToast: true,
                    active: 2,
                    collect: '已收藏',
                    icon: 'star-2',
                    text: '已收藏'
                })
            }, 1000);
        })
    }
    delmyCarCollect() {
        http.delmyCarCollect([this.state.id]).then(() => {
            setTimeout(() => {
                this.setState({
                    active: 3,
                    isToast: true,
                    collect: '收藏',
                    icon: 'star',
                    text: '取消收藏'
                })
            }, 1000)
        })
    }
    handleConfirm() {
        if (window.bridge) {
            let { list } = this.state
            this.handleCancel()
            window.bridge.callHandler('call', { 'tephone': list.creatorContact }, function responseCallback(res) { })
        } else {
            this.handleCancel()
        }
    }
    handleCancel() {
        this.setState({
            isShow: false
        }
        )
    }
    onCloseToast() {
        this.setState({
            isToast: false
        })
    }
    //  路由跳转车源详情
    handleToDetail(id) {
        let entId = this.state.id
        Taro.navigateTo({
            url: `/pages/carsourcedetails/carsourcedetails?id=${id}&&entId=${entId}`
        })
    }

    onLookHandle(url) {
        if (window.bridge) {
            let _images = [], i = 0
            _images.push(url)
            window.bridge.callHandler('previewPhoto', { "index": i, "images": _images }, function responseCallback() { })
        } else {
            this.setState({
                companycar: {
                    ...this.state.companycar,
                    itemStatus: true,
                    itemUrl: url
                }
            })
        }
    }

    onLookItem() {
        this.setState({
            companycar: {
                ...this.state.companycar,
                itemStatus: false,
                itemUrl: ''
            }
        })
    }

    handleEdit() {
        let { creatorId, list } = this.state
        if (creatorId === '2') {
            return Taro.showToast({
                title: '企业员工无法进行编辑',
                icon: 'none'
            })
        }
        Taro.navigateTo({
            url: `/pages/mycompanyintro/mycompanyintro?synopsis=${list.entInfo}`
        })
    }

    onRightHanlde() {
        let { creatorId } = this.state
        if (creatorId === '2') {
            return Taro.showToast({
                title: '企业员工无法查看',
                icon: 'none'
            })
        }
        const { knowUrl } = this.state
        sessionStorage.setItem('knowurl', JSON.stringify(knowUrl))
        Taro.navigateTo({
            url: '/pages/knowimages/knowimages'
        })
    }


    render() {
        let {
            active,
            current,
            isShow,
            collect,
            icon,
            isToast,
            list,
            item,
            text,
            footerStatus,
            scrollStyle,
            imageUrl1,
            imageUrl2,
            companycar,
            orderNumber
        } = this.state
        // item = []
        const { type, tab } = this.$router.params
        let tabList = +type == 2 ? [
            { title: '企业信息' },
            { title: '车源信息' },
        ] : [{ title: '企业信息' }, { title: '寻车信息' }, { title: '按揭信息' }]
        console.log("scrollStyle", scrollStyle)
        return (
            <View className='b_companydetail'>
                <DNavBar title={type ? '车商' : '企业详情'}></DNavBar>
                <View className='b_companydetail__box'>
                    <View className='b_companydetail__header'>
                        <View className='b_companydetail_company-introduction'>
                            {list.fileList}
                            <Image
                                src={imageUrl1}
                                className="b_companydetail_company-introduction_head-image"
                                // mode='widthFix'
                                onClick={this.onLookHandle.bind(this, imageUrl1)}
                            ></Image>
                            <View className='b_companydetail_company-introduction_head-news'>
                                <Text className='b_companydetail_company-introduction_head-news_company-name'>{list.entName || '--'}</Text>
                                {false && <Text className='b_companydetail_company-introduction_head-news_sale-volume'>成交订单量：{orderNumber}</Text>}
                            </View>
                        </View>
                    </View>
                    <View className='b_companydetail_tabs-navigation'>
                        <AtTabs
                            current={current}
                            scroll
                            tabList={tabList}
                            className='b_companydetail_tabs-navigation__header'
                            onClick={this.handleClick.bind(this)}
                        >
                            <AtTabsPane>
                                <View className='b_companydetail_tabs-navigation_tabsheader_card'>
                                    <View className='b_companydetail_tabs-navigation_tabsheader_card_list'>
                                        <Text className='b_companydetail_tabs-navigation_tabsheader_card_list_title'>所在区域</Text>
                                        <Text className='b_companydetail_tabs-navigation_tabsheader_card_list_describe'>{list.entDis || '--'}</Text>
                                    </View>
                                    <View className='b_companydetail_tabs-navigation_tabsheader_card_list'>
                                        <Text className='b_companydetail_tabs-navigation_tabsheader_card_list_title'>企业性质</Text>
                                        <Text className='b_companydetail_tabs-navigation_tabsheader_card_list_describe'>{list.entAtt || '--'}</Text>
                                    </View>
                                    <View className='b_companydetail_tabs-navigation_tabsheader_card_list'>
                                        <Text className='b_companydetail_tabs-navigation_tabsheader_card_list_title'>企业法人</Text>
                                        <Text className='b_companydetail_tabs-navigation_tabsheader_card_list_describe'>{list.entOwner || '--'}</Text>
                                    </View>
                                    <View className='b_companydetail_tabs-navigation_tabsheader_card_list'>
                                        <Text className='b_companydetail_tabs-navigation_tabsheader_card_list_title'>企业地址</Text>
                                        <Text className='b_companydetail_tabs-navigation_tabsheader_card_list_describe'>{list.entAddr || '--'}</Text>
                                    </View>
                                    <View className='b_companydetail_tabs-navigation_tabsheader_card_list'>
                                        <Text className='b_companydetail_tabs-navigation_tabsheader_card_list_title'>营业执照</Text>
                                        <Text className='b_companydetail_tabs-navigation_tabsheader_card_list_describe' onClick={this.onLookHandle.bind(this, imageUrl2)}>
                                            <AtAvatar image={imageUrl2} className="b_companydetail_tabs-navigation_tabsheader_card_list_describe_business-image"></AtAvatar>
                                        </Text>
                                    </View>
                                    <View className='b_companydetail_tabs-navigation_tabsheader_card_list' onClick={this.handleEdit.bind(this)}>
                                        <Text className='b_companydetail_tabs-navigation_tabsheader_card_list_title'>企业简介</Text>
                                        <Text className='b_companydetail_tabs-navigation_tabsheader_card_list_describe'>
                                            {list.entInfo || '--'}
                                            <AtIcon value="chevron-right" size="18" />
                                        </Text>
                                    </View>
                                    <View className='b_companydetail_tabs-navigation_tabsheader_card_list' onClick={this.onRightHanlde.bind(this)}>
                                        <Text className='b_companydetail_tabs-navigation_tabsheader_card_list_title'>资料图片</Text>
                                        <Text className='b_companydetail_tabs-navigation_tabsheader_card_list_describe'>
                                            &nbsp;
                                            <AtIcon value="chevron-right" size="18" />
                                        </Text>
                                    </View>
                                </View>
                            </AtTabsPane>
                            <AtTabsPane>
                                <View className='b_companydetail__box'>
                                    <View className='b_companydetail__content'>
                                        {
                                            item.length > 0 && <ScrollView
                                                scrollY
                                                scrollWithAnimation
                                                lowerThreshold='20'
                                                style={`height:${scrollStyle - 146}PX !important`}
                                                onScrollToLower={this.onScroll}>
                                                {item && item.map((item, i) => {
                                                    return <DCarInfo
                                                        key={i}
                                                        carmoney={item.carOfferPrice}
                                                        nameList={[item.carDataModel]}
                                                        infoList={[item.carSourceType, item.carEmissionStd, item.carSourcePt, '外观颜色', item.carOutColor,]}
                                                        place={list.carSourceAddr}
                                                        money={item.carGuiPrice}
                                                        icon={item.carDataBrandLogo}
                                                        company={item.entName + (item.entDis ? '(' + (item.entDis) + ')' : '')}
                                                        clock={item.ago}
                                                        onDetail={this.handleToDetail.bind(this, item.id)}
                                                    >
                                                    </DCarInfo>
                                                })
                                                }
                                                {
                                                    footerStatus && <View className='b_companydetail__more'>暂无更多</View>
                                                }

                                            </ScrollView>
                                        }

                                    </View>

                                </View>
                            </AtTabsPane>
                            {/* {+type == 1 &&  */}
                            <AtTabsPane >
                                <MortageList status={'cardealer'} active={current} />
                            </AtTabsPane>}
                        </AtTabs>
                        {+current == 1 && item.length == 0 && <DItemError></DItemError>}
                    </View>
                </View>
                <DModal
                    isShow={isShow}
                    title='提示'
                    text={`确认拨打${list.creatorContact.substr(0, 3)}-${list.creatorContact.substr(3, 4)}-${list.creatorContact.substr(7, 4)}吗`}
                    onFirst={this.handleCancel.bind(this)}
                    onLast={this.handleConfirm.bind(this)}
                    onCancel={this.handleCancel.bind(this)}
                >
                </DModal>

                <AtToast isOpened={isToast} text={text} icon={icon} duration='800' onClose={this.onCloseToast.bind(this)}></AtToast>

                <DLookImages status={companycar.itemStatus} url={companycar.itemUrl} onLookHandle={this.onLookItem.bind(this)}></DLookImages>
                {current === 0 &&
                    <AtTabBar
                        className='b_companydetail__tabbar'
                        fixed tabList={[
                            // { title: '私信', image: icon_message },
                            { title: '电话', image: icon_phone },
                            { title: `${collect}`, image: icon_star, selectedImage: icon_star2 }
                        ]}
                        onClick={this.onHandleActive.bind(this)}
                        current={active}>
                    </AtTabBar>}
            </View>

        )
    }
}
